﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

namespace CMS6Tools.Common
{
    public class TypedConfigurationSection : ConfigurationSection, IObjectWithType
    {
        #region Const
        protected const string TypeNamePropertyName = "type";
        #endregion

        #region Fields
        protected AssemblyQualifiedTypeNameConverter typeConverter = null;
        #endregion

        #region Ctors
        public TypedConfigurationSection()
            : base()
        {
            typeConverter = new AssemblyQualifiedTypeNameConverter();
        }

        public TypedConfigurationSection(Type type)
            : this()
        {
            Type = type;
        }
        #endregion

        #region Properties
        public virtual Type Type
        {
            get { return (Type)typeConverter.ConvertFrom(TypeName); }
            set { TypeName = typeConverter.ConvertToString(value); }
        }

        [ConfigurationProperty(TypeNamePropertyName, IsRequired = true)]
        public virtual string TypeName
        {
            get { return (string)this[TypeNamePropertyName]; }
            set { this[TypeNamePropertyName] = value; }
        }
        #endregion
    }

    public class TypedConfigurationSection<T> : TypedConfigurationSection, IInstancable<T>
    {
        #region Ctors
        public TypedConfigurationSection()
            : base()
        {
        }

        public TypedConfigurationSection(Type type)
            : base(type)
        { 
        }

        public TypedConfigurationSection(T target)
            : this(typeof(T))
        {
        }
        #endregion

        public virtual T CreateInstance()
        {
            return default(T);
        }
    }
}
